from rest_framework import serializers
from .models import System, UserProfile
from utils.system_format import get_memory_usage_percentage, get_disk_usage_percentage, get_uptime_formatted, \
    format_bytes
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Permission, ContentType, Group


class SystemInfoSerializer(serializers.ModelSerializer):
    memory_usage_formatted = serializers.SerializerMethodField()
    disk_usage_formatted = serializers.SerializerMethodField()
    uptime_formatted = serializers.SerializerMethodField()
    system_status = serializers.SerializerMethodField()

    class Meta:
        model = System
        fields = '__all__'

    def get_memory_usage_formatted(self, obj):
        used = format_bytes(obj.get("memory_used", 0), "MB")
        total = format_bytes(obj.get("memory_total", 0), "MB")
        return f"{used} / {total}"

    def get_disk_usage_formatted(self, obj):
        used = format_bytes(obj.get("disk_used", 0), "GB")
        total = format_bytes(obj.get("disk_total", 0), "GB")
        return f"{used} / {total}"

    def get_uptime_formatted(self, obj):
        return get_uptime_formatted(obj)

    def get_system_status(self, obj):
        mem_usage = get_memory_usage_percentage(obj)
        disk_usage = get_disk_usage_percentage(obj)
        if obj.get("cpu_usage") > 80 or mem_usage > 85 or disk_usage > 90:
            return "告警"
        elif obj.get("cpu_usage") > 60 or mem_usage > 70 or disk_usage > 80:
            return "注意"
        return "健康"


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = [
            'id', "password", "is_superuser", "username",
            "email", "is_active", "phone"
            # 'groups', 'user_permissions'
        ]
        extra_kwargs = {
            'username': {"min_length": 3, 'max_length': 10},
            'password': {"write_only": True},
            'is_superuser': {'default': False},
            'is_active': {'default': False}
        }

    def validate_password(self, value):
        if 5 <= len(value) <= 10:
            return make_password(value)
        raise serializers.ValidationError('密码长度为5到10个字符')


class ContentTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContentType
        fields = '__all__'


class PermSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = '__all__'

    content_type = ContentTypeSerializer(read_only=True)


class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'
